﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Application.Service.OrderInfo;
using Admin.NET.Application.Service.WcsService;
using Mapster;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WCS.Application.Entity.Warehous;
using WCS.Application.Service.Materialssuance;

namespace WCS.Application.Service.Maintenance;
public class MaintenanceService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<MaintenanceEntity> _maintenancce;

    private readonly UserManager _userinfo;
    public MaintenanceService(SqlSugarRepository<MaintenanceEntity> maintenancce, UserManager userinfo)
    {
        _maintenancce = maintenancce;
        _userinfo = userinfo;

    }


    /// <summary>
    /// 获取地图维护信息 🔖
    /// </summary>
    /// <param name="taskInput"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "GetMaintenancePageList"), HttpPost]
    public async Task<SqlSugarPagedList<MaintenanceEntity>> GetMaintenancePageList(MaintenanceDto taskInput)
    {
        // status用枚举判断了
        var list = await _maintenancce.AsQueryable()
                .WhereIF(!string.IsNullOrWhiteSpace(taskInput.Type), u => u.Type.Equals(taskInput.Type))
                .WhereIF(!string.IsNullOrWhiteSpace(taskInput.Abscissa.ToString()), u => u.Abscissa.Equals(taskInput.Abscissa))
                .WhereIF(!string.IsNullOrWhiteSpace(taskInput.Coordinate.ToString()), u => u.Coordinate.Equals(taskInput.Coordinate))
                .WhereIF(!string.IsNullOrWhiteSpace(taskInput.Vertical.ToString()), u => u.Vertical.Equals(taskInput.Vertical))
                .OrderBy(u => u.CreateTime, SqlSugar.OrderByType.Desc) // 再按CreateTime降序排序
                .ToPagedListAsync(taskInput.Page, taskInput.PageSize);
        return list;
    }

    /// <summary>
    /// 获取地图维护信息 🔖
    /// </summary>
    /// <param name="taskInput"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "GetMaintenanceList"), HttpPost]
    public async Task<List<MaintenanceEntity>> GetMaintenanceList(MaintenanceDto taskInput)
    {
        Expression<Func<MaintenanceEntity, bool>> expression = whereExp =>
                 (taskInput.Type.GetIsEmptyOrNull() || whereExp.Type.Contains((taskInput.Type.Trim())))
                 && (taskInput.Abscissa.GetIsEmptyOrNull() || whereExp.Abscissa.Equals(taskInput.Abscissa))
                 && (taskInput.Vertical.GetIsEmptyOrNull() || whereExp.Vertical.Equals(taskInput.Vertical));

        var list = await _maintenancce.AsQueryable().WhereIF(expression != null, expression).OrderBuilder(taskInput).ToListAsync();
        return list;
    }

    /// <summary>
    /// 添加维护记录
    /// </summary>
    /// <param name="Input"></param>
    /// <returns></returns>

    [ApiDescriptionSettings(Name = "InsertMaintenance"), HttpPost]

    public async Task<long> InsertMaintenance(AddMaintenanceInput Input)
    {
        #region 唯一索引
        Expression<Func<MaintenanceEntity, bool>> whereExpression = whereExp =>
                    whereExp.Id.Equals(Input.Abscissa) && whereExp.Abscissa.Equals(Input.Abscissa);
        #endregion
        var data = await _maintenancce.GetFirstAsync(whereExpression);
        if (data != null)
        {
            throw Oops.Oh(10001, "该记录已存在");
        }


        var entity = Input.Adapt<MaintenanceEntity>();

        await _maintenancce.AsInsertable(entity).ExecuteCommandAsync();
        return entity.Id;
    }

    /// <summary>
    /// 修改维护地图
    /// </summary>
    /// <param name="entity"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "UpdateMaintenance"), HttpPost]

    public async Task<int> UpdateMaintenance(UpdateMaintenanceDtoInput entity)
    {
        SerilogHelper.WriteLog("MaintenanceService", "修改维护地图开始", JsonConvert.SerializeObject(entity));
        #region 唯一索引
        Expression<Func<MaintenanceEntity, bool>> whereExpression = whereExp =>
                    whereExp.Id.Equals(entity.Id);
        #endregion
        var OrderInfo = await _maintenancce.GetFirstAsync(u => u.Id == entity.Id);

        try
        {
            if (OrderInfo != null)
            {


                //对实体进行赋值
                entity.UpdateUserId = _userinfo.UserId;
                entity.UpdateTime = DateTime.Now;
                entity.UpdateUserName = _userinfo.RealName;
            }
            else
            {

                throw Oops.Oh(ErrorCodeEnum.D1002);
            }
        }
        catch (Exception error)
        {
            throw Oops.Oh("修改出入订单出现错误：" + error.Message + "");
        }
        //api已转为entity
        var updateEntity = entity.Adapt<MaintenanceEntity>();
        SerilogHelper.WriteLog("MaintenanceService", "修改维护地图结束", JsonConvert.SerializeObject(updateEntity));

       return  await _maintenancce.AsUpdateable(updateEntity).ExecuteCommandAsync();
        //IgnoreColumns(ignoreAllNullColumns: true)

    }
    /// <summary>
    /// 批量删除
    /// </summary>
    /// <param name="inputList"></param>
    /// <returns></returns>
    [UnitOfWork]
    [ApiDescriptionSettings(Name = "BatchDeleteMaintenance"), HttpDelete]
    [DisplayName("批量删除")]
    public virtual async Task<int> BatchDeleteMaintenance(List<DeleteMaintenanceInput> inputList)
    {
        #region "校验"
        foreach (var input in inputList)
        {
            Expression<Func<MaintenanceEntity, bool>> whereExpression = whereExp =>
                        whereExp.Id.Equals(input.Id)
                   ;
            var data = await _maintenancce.GetFirstAsync(whereExpression);
            if (data == null)
            {
                throw Oops.Oh("该记录不存在");
            }

            // *****校验是否有其他表使用该记录*****
        }
        #endregion

        var deleteEntity = inputList.Adapt<List<MaintenanceEntity>>();
        return await _maintenancce.AsDeleteable()
            .Where(deleteEntity)
            .ExecuteCommandAsync();
    }
    /// <summary>
    /// 下载模版
    /// </summary>
    /// <returns></returns>
    [UnitOfWork]
    [DisplayName("下载模版")]
    [HttpGet]
    public virtual async Task<IActionResult> DownloadMaintenance()
    {
        return await Task.Run(() =>
        {
            #region "校验"
            string fileName = "Maintenance.xlsx";
            string filePath = $"{AppDomain.CurrentDomain.BaseDirectory}/Template/{fileName}";
            if (!File.Exists(filePath))
            {
                throw Oops.Oh(10002, "找不到该模板：" + filePath);
            }
            #endregion

            var path = Path.Combine(filePath);
            return new FileStreamResult(new FileStream(path, FileMode.Open), System.Net.Mime.MediaTypeNames.Application.Octet)
            {
                FileDownloadName = fileName
            };
        });
    }
    /// <summary>
    /// 导出设备信息为 Excel
    /// </summary>
    [UnitOfWork]
    [DisplayName("导出设备为Excel")]
    [ApiDescriptionSettings(Name = "MaintenanceExcel"), HttpPost]
    public virtual async Task<IActionResult> MaintenanceExcel([FromBody] MaintenanceDto input)
    {
        var list = await GetMaintenanceList(input);

        // 使用 NPOI 创建 Excel 文件
        var workbook = new NPOI.XSSF.UserModel.XSSFWorkbook();
        var sheet = workbook.CreateSheet("地图点位维护");

        // 创建表头
        var headerRow = sheet.CreateRow(0);
        headerRow.CreateCell(0).SetCellValue("类型");
        headerRow.CreateCell(1).SetCellValue("横坐标");
        headerRow.CreateCell(2).SetCellValue("纵坐标");
        headerRow.CreateCell(3).SetCellValue("垂直坐标");
        headerRow.CreateCell(4).SetCellValue("对应点位");
        headerRow.CreateCell(5).SetCellValue("启用状态");
        headerRow.CreateCell(6).SetCellValue("备注");
        

        // 填充数据
        for (int i = 0; i < list.Count; i++)
        {
            var row = sheet.CreateRow(i + 1);
            var device = list[i];
            row.CreateCell(0).SetCellValue(device.Type);
            row.CreateCell(1).SetCellValue(device.Abscissa);
            row.CreateCell(2).SetCellValue(device.Coordinate);
            row.CreateCell(3).SetCellValue(device.Vertical);
            row.CreateCell(3).SetCellValue(device.Point);
            row.CreateCell(3).SetCellValue(device.Enable==StatusEnum.Enable?"启用":"停用");
            row.CreateCell(3).SetCellValue(device.Explanatory);
        }

        // 将 Excel 文件写入内存流
        using var memoryStream = new MemoryStream();
        workbook.Write(memoryStream);
        var bytes = memoryStream.ToArray();

        // 返回文件结果
        return new FileContentResult(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        {
            FileDownloadName = "MaintenanceExcel.xlsx"
        };
    }
    /// <summary>
    /// 导地图维护
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>

    [UnitOfWork]
    [DisplayName("导入地图维护")]
    [ApiDescriptionSettings(Name = "ImportMaintenance"), HttpPost]
    public virtual async Task<List<ImportMaintenanceOutput>> ImportMaintenance([Required] IFormFile file)
    {

        if (file != null)
        {
            var fileDir = AppDomain.CurrentDomain.BaseDirectory + @"ImportFile";
            if (!Directory.Exists(fileDir))

            {
                Directory.CreateDirectory(fileDir);
            }
            //文件名称
            string fileName = file.FileName;
            //文件类型
            string fileType = file.FileName.Substring(fileName.LastIndexOf("."));
            //上传的文件的路径
            string filePath = fileDir + $@"/{fileName}";
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                file.CopyTo(fs);
            }

            if (fileType == ".xlsx" || fileType == ".xls")
            {
                ExcelHelper eh = new ExcelHelper(filePath);
                DataTable dt = eh.ExcelToDataTable("", true);
                eh.Dispose();
                if (dt == null || dt.Rows.Count == 0)
                {
                    throw Oops.Oh("文件为空！");
                }

                #region "校验模板字段"
                if (!dt.Columns.Contains("类型") || !dt.Columns.Contains("横坐标") || !dt.Columns.Contains("纵坐标") || !dt.Columns.Contains("垂直坐标") || !dt.Columns.Contains("对应点位") || !dt.Columns.Contains("启用状态") || !dt.Columns.Contains("备注"))
                {
                    throw Oops.Oh("文件模板错误！请重新下载模板");
                }
                var orderid = string.Empty;

                //不存在订单编号自己生成
                // orderid = await GenerateOrderIdAsync();

                #endregion

                List<ImportMaintenanceOutput> listLoad = new List<ImportMaintenanceOutput>();
                int i = 0;
                foreach (DataRow row in dt.Rows)
                {
                    i++;
                    //校验关联信息
                    ImportMaintenanceOutput orderInfoEntity = new ImportMaintenanceOutput
                    {
                        Type = row["类型"].GetCString(),
                        Abscissa = row["横坐标"].GetCInt(),
                        Coordinate = row["纵坐标"].GetCInt(),
                        Point = row["对应点位"].GetCString(),
                        Vertical = row["垂直坐标"].GetCInt(),
                        Enable = (StatusEnum)row["启用状态"].GetCInt(),
                        Explanatory = row["备注"].GetCString(),

                    };
                    #region "校验必填项"

                    #endregion
                    //用唯一索引查询非重复
                    Expression<Func<MaintenanceEntity, bool>> whereExpression = whereExp =>
                        whereExp.Abscissa.Equals(orderInfoEntity.Abscissa);
                    var data = await _maintenancce.GetFirstAsync(whereExpression);
                    if (data == null)
                    {
                        #region "自定义校验"

                        orderInfoEntity.CreateUserId = _userinfo.UserId;
                        orderInfoEntity.CreateTime = DateTime.Now;
                        orderInfoEntity.CreateOrgId = _userinfo.OrgId;
                        orderInfoEntity.CreateUserId = _userinfo.UserId;
                        orderInfoEntity.CreateUserName = _userinfo.RealName;

                        data = _maintenancce.Adapt(orderInfoEntity);
                        #endregion

                        var rtAdd = await _maintenancce.AsInsertable(data).ExecuteCommandAsync();
                        if (rtAdd != 1)
                        {
                            orderInfoEntity.ResultCode = 10004;
                            orderInfoEntity.Message = "插入失败";
                        }
                    }
                    else
                    {
                        #region "自定义校验"  

                        data.UpdateUserId = _userinfo.UserId;
                        data.UpdateTime = DateTime.Now;
                        data.UpdateUserName = _userinfo.RealName;
                        data.Type = orderInfoEntity.Type;
                        data.Abscissa = orderInfoEntity.Abscissa;
                        data.Coordinate = orderInfoEntity.Coordinate;
                        data.Vertical = orderInfoEntity.Vertical;
                        data.Enable = orderInfoEntity.Enable;
                        data.Explanatory = orderInfoEntity.Explanatory;
                        // 使用 Mapster 的 Adapt 方法将 orderInfoEntity 的值替换到 data 中  

                        //不能用Adapt替换因为importPosition中没主键

                        var order = data.Adapt(orderInfoEntity);
                        var rtUpdate = await _maintenancce.AsUpdateable(order).ExecuteCommandAsync();
                        if (rtUpdate != 1)
                        {
                            orderInfoEntity.ResultCode = 10004;
                            orderInfoEntity.Message = "更新失败";
                        }
                    }

                    if (orderInfoEntity.ResultCode != 200)
                        listLoad.Add(orderInfoEntity);
                }

                // 返回导入失败数据
                if (listLoad.Count > 0)
                {
                    return listLoad;
                }
            }
            else
            {
                throw Oops.Oh(10002, "文件内容为空！");
            }
        }
        else
        {
            throw Oops.Oh(10002, "请选择文件！");
        }
        return null;
    }
    #endregion
}
